package chatglm

import (
	"chatgpt/ai/models"
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/plugin/httpsrv"
	"io"
	"net/http"
	"strconv"
	"strings"
)

var Search models.Search

func init() {
	Search.SystemWord = GLM_PROMPT_PRIFIX
}

type ResponseDesc struct {
	MsgCode code.CODENO
	Data    interface{}
	Desc    string
	Tokens  int
}

func RemoteApi(w http.ResponseWriter, url_path string, m map[string]any, dest io.Writer) (code.CODENO, *helper.ResponseDesc) {
	cnf := helper.Config().Sub("Server")
	//addr_url := cnf.GetString("RmmoteAiUrl")

	res, resok := dest.(*helper.ResponseDesc)

	m["api_key"] = strings.ReplaceAll(cnf.GetString("AuthToken"), "#", "%23")
	//param := fmt.Sprintf("?api_key=%v%v", strings.ReplaceAll(cnf.GetString("AuthToken"), "#", "%23"), pa1)
	url := cnf.Sub("ChatGLM").GetString("RemoteAi") + url_path
	//dddd := "http://localhost:18060/question/origin?api_key=API-TD.DFD%23$D$GDL-2D%23dfCDDG@2*DFWMBV%23DFEDF&q=who%20are%20you&model=&size=512x512"
	err := httpsrv.PostStream(w, url, m, res)

	if err != nil {
		logq.Error("ChatGLM.Remote err: ", err)
		return code.SERVER_ERR, res
	}
	if !resok {
		return code.SUCCESS, &helper.ResponseDesc{
			MsgCode: code.SUCCESS,
		}
	}
	if res.MsgCode != code.SUCCESS {
		return res.MsgCode, res
	}
	//data := res.Data
	return res.MsgCode, res
}

func CompletionRemote(w http.ResponseWriter, url_path string, q string, m map[string]string) (code.CODENO, *helper.ResponseDesc) {
	res := helper.ResponseDesc{MsgCode: code.SUCCESS}
	return RemoteApi(w, url_path, remotePrefix(m), &res)
}

func CompletionRemoteString(w http.ResponseWriter, url_path string, q string, m map[string]string) (code.CODENO, *helper.ResponseDesc) {
	return RemoteApi(w, url_path, remotePrefix(m), nil)
}

func remotePrefix(m map[string]string) map[string]any {
	cnf := helper.Config().Sub("ChatGLM").Sub("completion")
	m_any := map[string]any{}
	for k, v := range m {
		m_any[k] = v
	}
	m_any["temperature"], _ = strconv.ParseFloat(cnf.GetString("temperature"), 64)
	m_any["top_p"], _ = strconv.ParseFloat(cnf.GetString("top_p"), 64)

	if _, ok := m["zhishiku"]; !ok {
		m_any["zhishiku"] = cnf.GetString("zhishiku")
	}
	return m_any
}
